package com.ocom.payconfig.utils;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ApiSignGenerator {

    private String secretKey;

    private String nonce;

    private Long timestamp;

    private String appId;

    private Map<String, Object> paramMap;

    private String paramJson;

    public String generate(Map<String, Object> paramMap) {
        this.paramMap = paramMap;
        paramJson = genParamJson();
        log.info("sign摘要字符串: {}", this);
        Digester sha1Digester = new Digester(DigestAlgorithm.SHA1);
        return sha1Digester.digestHex(this.toString());
    }

    @Override
    public String toString() {
        return "secretKey=" + secretKey +
                ",nonce=" + nonce +
                ",timestamp=" + timestamp +
                ",appId=" + appId +
                ",paramJson=" + paramJson;
    }

    private String genParamJson() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            // 序列化JSON字符串
            return objectMapper.writeValueAsString(paramMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

}
